#include "MysqlHelper.h"

#define LOGGER_NAME "shadow.smysql.mysqlhelper"

MysqlHelper::MysqlHelper() {
		_logger = log4cxx::Logger::getLogger(LOGGER_NAME);
}

MysqlHelper::~MysqlHelper() {}


int MysqlHelper::query(MYSQL * mysql, const char * sql, const int sql_len) {
		if (NULL == sql || NULL == mysql || sql_len < 1) {
				LOG4CXX_ERROR(_logger, "null mysql query");
				return -1;
		}
		int res = mysql_real_query(mysql, sql, sql_len);
		if (0 != res) {
				LOG4CXX_ERROR(_logger, "mysql query error, sql:" << sql << ", mysql error:" << mysql_error(mysql));
				return -2;
		}
		return 1;
}

int MysqlHelper::escape_string(MYSQL * mysql, string & to, const char * from, const int from_len) {
		if (NULL == mysql || NULL == from || from_len < 1) {
				LOG4CXX_ERROR(_logger, "escape mysql string error, invalid args");
				return -1;
		}
		int to_len = 2 * from_len + 1;
		char * t = new char[to_len];
		mysql_real_escape_string(mysql, t, from, from_len);
		to = t;
		delete[] t;
		return 1;
}

MYSQL_RES * MysqlHelper::store_result(MYSQL * mysql, const char * sql) {
		if (NULL == mysql) {
				LOG4CXX_ERROR(_logger, "mysql store result error, invalid MYSQL handle");
				return NULL;
		}
		MYSQL_RES * res = mysql_store_result(mysql);
		if (NULL == res) {
				LOG4CXX_ERROR(_logger, "mysql store result error, mysql error:" << mysql_error(mysql) << ", sql:" << \
								(NULL == sql ? "NULL" : sql));
			   	return NULL;
		}
		return res;
}
